package cn.ekuma.epos.panel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;

import javax.swing.AbstractListModel;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;

import org.jdesktop.swingx.JXTable;
import org.ofsm.IEvent;
import org.ofsm.IStateChangeListener;
import org.ofsm.impl.FileFiniteStateMachine;

import cn.ekuma.data.dao.I_ParentNode;
import cn.ekuma.data.ui.swing.AbstractDAOJEditor;
import cn.ekuma.data.ui.swing.AbstractDTOTableModel;
import cn.ekuma.data.ui.swing.ParentNodeChangeListener;


import com.openbravo.bean.shard.I_StateFollow;
import com.openbravo.bean.shard.I_StateObject;
import com.openbravo.data.basic.BasicException;
import com.openbravo.format.Formats;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.bean.I_AppUser;

public abstract class AbstractJStateObjectChildDAOEditorPanel<K> extends javax.swing.JPanel implements ParentNodeChangeListener<K> {
   
    protected AbstractDTOTableModel tableModel;
    FileFiniteStateMachine stateMachine;
    protected String stateProcessName;
    
	private JButton btnNewButton_1;
	private JButton btnNewButton_2;
	private String relationMan;
	private String relationID;
	protected I_AppUser user;
	private I_StateObject parentStateObject;
	
    public AbstractJStateObjectChildDAOEditorPanel(AbstractDTOTableModel tableModel,I_AppUser user,String stateProcessName) {
    	setPreferredSize(new Dimension(650, 170));
        initComponents();
        
        stateMachine=new FileFiniteStateMachine();
        jXTable1.setModel(tableModel);
        this.stateProcessName=stateProcessName;
        this.user=user;
    }
    
    public abstract void init() throws BasicException;
    

    public void initStateMachine(byte[] bf) throws BasicException{
            if (bf != null) {
                ByteArrayInputStream btStream = new ByteArrayInputStream(bf);
                try {
                    stateMachine.init(btStream);
                    //stateMachine.setCurrentState(currentState);
                } catch (Exception ex) {
                   throw new BasicException(ex);
                }
            }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jXTable1 = new org.jdesktop.swingx.JXTable();

        setLayout(new java.awt.BorderLayout());

        jXTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jXTable1);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
        
        jXTable1.setColumnControlVisible(true);
        jXTable1.setAutoCreateRowSorter(true);
        
        panel = new JPanel();
        add(panel, BorderLayout.EAST);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        
        panel_1 = new JPanel();
        panel_1.setPreferredSize(new Dimension(300, 10));
        panel.add(panel_1);
        panel_1.setLayout(new BorderLayout(0, 0));
        
        textArea = new JTextArea();
        textArea.setBorder(new TitledBorder(null, AppLocal.getIntString("label.I_StateFollow.memo"), TitledBorder.LEADING, TitledBorder.TOP, null, null));
        panel_1.add(textArea, BorderLayout.CENTER);
        
        panel_3 = new JPanel();
        panel_3.setPreferredSize(new Dimension(10, 90));
        panel_1.add(panel_3, BorderLayout.SOUTH);
        panel_3.setLayout(null);
        
        JLabel label = new JLabel(AppLocal.getIntString("label.I_StateFollow.nextTime"));
        label.setBounds(10, 10, 85, 15);
        panel_3.add(label);
        
        txtNextTime = new JTextField();
        txtNextTime.setBounds(91, 10, 134, 21);
        panel_3.add(txtNextTime);
        txtNextTime.setColumns(10);
        
        JLabel label_1 = new JLabel(AppLocal.getIntString("label.I_StateFollow.relationMan"));
        label_1.setBounds(10, 35, 85, 15);
        panel_3.add(label_1);
        
        txtRelationMan = new JTextField();
        txtRelationMan.setEditable(false);
        txtRelationMan.setBounds(91, 35, 134, 21);
        panel_3.add(txtRelationMan);
        txtRelationMan.setColumns(10);
        
        JLabel label_2 = new JLabel(AppLocal.getIntString("label.I_StateFollow.priority"));
        label_2.setBounds(10, 60, 85, 15);
        panel_3.add(label_2);
        
        btnNewButton_1 = new JButton("");
        btnNewButton_1.setIcon(new ImageIcon(AbstractJStateObjectChildDAOEditorPanel.class.getResource("/com/openbravo/images/kdmconfig.png")));
        btnNewButton_1.setBounds(228, 35, 51, 23);
        panel_3.add(btnNewButton_1);
        
        btnNewButton_2 = new JButton("");
        btnNewButton_2.setIcon(new ImageIcon(AbstractJStateObjectChildDAOEditorPanel.class.getResource("/com/openbravo/images/1day.png")));
        btnNewButton_2.setBounds(228, 10, 51, 23);
        panel_3.add(btnNewButton_2);
        
        txtPriority = new JTextField();
        txtPriority.setBounds(91, 60, 188, 21);
        panel_3.add(txtPriority);
        txtPriority.setColumns(10);
        
        panel_2 = new JPanel();
        panel_2.setPreferredSize(new Dimension(80, 10));
        panel.add(panel_2);
        panel_2.setLayout(new BorderLayout(0, 0));
        
        scrollPane = new JScrollPane();
        panel_2.add(scrollPane, BorderLayout.CENTER);
        
        jEventList = new JList();
        jEventList.setBorder(new TitledBorder(null, AppLocal.getIntString("orderState.ableEvents"), TitledBorder.LEADING, TitledBorder.TOP, null, null));
        jEventList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        scrollPane.setViewportView(jEventList);
        
        btnNewButton = new JButton(AppLocal.getIntString("label.run"));
        btnNewButton.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		IEvent select=(IEvent) jEventList.getSelectedValue();
                if(select!=null){
                   stateMachine.fireEvent(select);
                   resert();
                   searchAbleEventList();
                }
        	}
        });
        btnNewButton.setPreferredSize(new Dimension(40, 35));
        panel_2.add(btnNewButton, BorderLayout.SOUTH);
        updateUI(false);
    }// </editor-fold>//GEN-END:initComponents

    public void addStateChangeListener(IStateChangeListener l) {
    	stateMachine.addStateChangeListener(l);
    }

    public void delStateChangeListener(IStateChangeListener l) {
    	stateMachine.delStateChangeListener(l);
    }
    

   public JXTable getJXTable(){
        return  jXTable1;
   }

    private javax.swing.JScrollPane jScrollPane1;
    protected org.jdesktop.swingx.JXTable jXTable1;
    private JPanel panel;
    private JPanel panel_1;
    private JPanel panel_2;
    private JScrollPane scrollPane;
    private JList jEventList;
    private JButton btnNewButton;
    protected JTextArea textArea;
    private JPanel panel_3;
    protected JTextField txtNextTime;
    protected JTextField txtRelationMan;
    private JTextField txtPriority;
    // End of variables declaration//GEN-END:variables


    public void updateUI(boolean editAble) {
        jXTable1.setEditable(editAble);
        btnNewButton.setEnabled(editAble);
        jEventList.setEnabled(editAble);
        txtNextTime.setEditable(editAble);
        btnNewButton_1.setEnabled(editAble);
        btnNewButton_2.setEnabled(editAble);
    }
    
    public  void  updateObj(I_StateFollow obj) throws BasicException{
    	obj.setMemo(textArea.getText());
    	obj.setRelationID(relationID);
    	obj.setRelationMan(relationMan);
		obj.setPriority((Integer) Formats.INT.parseValue(txtPriority.getText()));
		obj.setUserId(user.getId());
    	obj.setCallTime(new Date());
    	obj.setNextTime((Date) Formats.TIMESTAMP.parseValue(txtNextTime.getText()));
    	obj.setState(stateMachine.getCurrentState().getName());
    	
    }

    protected void resert(){
    	textArea.setText(null);
    	relationID=null;
    	relationMan=null;
    	txtPriority.setText("1");
    	txtNextTime.setText(null);
    }
    List<IEvent> ableEvents;
    
    protected void searchAbleEventList(){
    	  stateMachine.setCurrentState(this.parentStateObject.getState());
          ableEvents = getUserStateProcessEvents();
          jEventList.setModel(new AbstractListModel() {
              public int getSize() {
                  return ableEvents.size();
              }

              public Object getElementAt(int index) {
                  return ableEvents.get(index);
              }
          });
    }

    abstract List<IEvent> getUserStateProcessEvents();
    
	@Override
	public void parentNodeValueChange(int state, I_ParentNode<K> parent) {
		parentStateObject=(I_StateObject) parent.getParentKey();
		updateUI(state==AbstractDAOJEditor.STATE_Edit);
		resert();
		searchAbleEventList();
	}
}
